package com.ericsson.middleware.slsp;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.core.MediaType;

import org.apache.commons.httpclient.HttpStatus;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.ericsson.middleware.PropertiesProvider;
import com.ericsson.middleware.utils.JsonUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;

public class SmartLightningClient {

	static String SESSION_ID = "";

	private final static Logger LOGGER = Logger
			.getLogger(SmartLightningClient.class.getName());
	
	public String getSessionId() {
		return SESSION_ID;
	}

	public boolean refreshLampSessionID() {
		try {

			Client client = Client.create();

			Builder webResource = client
					.resource(PropertiesProvider.getSESSION_ID_PROVIDER_URL())
					.type(MediaType.APPLICATION_JSON)
					.header(PropertiesProvider.getHEADER_XDREAM_FACTORY_APPLICATION_NAME(),
							PropertiesProvider.getHEADER_XDREAM_FACTORY_APPLICATION_NAME_VALUE());

			ClientResponse response = webResource.type(
					MediaType.APPLICATION_JSON).post(ClientResponse.class,
							PropertiesProvider.getAUTHENTICATION_RAW_DATA());

			if (response.getStatus() != HttpStatus.SC_OK) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatus());
			}

			String output = response.getEntity(String.class);

			SESSION_ID = ((IntelimotionLogin) JsonUtil.fromJson(output,
					IntelimotionLogin.class)).getSessionId();
			System.out.println("Jsonutil session id: " + SESSION_ID);
			return true;

		} catch (Exception e) {
			LOGGER.log(Level.SEVERE, "Failed to get lamps session id ");
		}
		return false;
	}

	public RecordList getLamps() {

		try {
			Client client = Client.create();

			Builder webResource = client
					.resource(PropertiesProvider.getLAMPS_STATUS_PROVIDER_URL())
					.header(PropertiesProvider.getHEADER_XDREAM_FACTORY_APPLICATION_NAME(),
							PropertiesProvider.getHEADER_XDREAM_FACTORY_APPLICATION_NAME_VALUE())
					.header(PropertiesProvider.getHEADER_XDREAM_FACTORY_SESSION_TOKEN(), SESSION_ID);

			ClientResponse response = webResource.type("application/json").get(
					ClientResponse.class);

			if (response.getStatus() != HttpStatus.SC_OK) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatus());
			}

			String responseJson = response.getEntity(String.class);			
			RecordList lampList = ((RecordList) JsonUtil.fromJson(responseJson,
					RecordList.class));
					
			// parameters to send to CB
			setAdditionalAttributes(responseJson, lampList);		

			return lampList;

		} catch (Exception e) {
			LOGGER.log(Level.SEVERE, "Failed to get lamps status");
		}
		return null;
	}

	public String setLamps(String id) {

		// TODO
		try {

			Client client = Client.create();

			WebResource webResource = client
					.resource("http://localhost:8080/SmartLightning/lamps");

			ClientResponse response = webResource.type("application/json")
					.post(ClientResponse.class, id);

			if (response.getStatus() != HttpStatus.SC_OK) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatus());
			}

			System.out.println("Output from Server .... \n");
			String output = response.getEntity(String.class);
			System.out.println(output);

		} catch (Exception e) {
			LOGGER.log(Level.SEVERE, "Failed to set lamps status");

		}
		return null;

	}
	
	private void setAdditionalAttributes(String responseJson, RecordList lampList) throws JSONException{
		JSONObject jsonResponse = new JSONObject(responseJson);
		JSONArray jsonMainNode = jsonResponse.optJSONArray("record");
		// Process each JSON Node 
		int lengthJsonArr = jsonMainNode.length();
		for (int i = 0; i < lengthJsonArr; i++) {
			// Get Object for each JSON node
			JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

			// Fetch node values
			for (String jsonParam : PropertiesProvider.getJSON_LAMP_ATTRIBUTES()) {
				lampList.getRecord().get(i).setAdditionalProperty(jsonParam, jsonChildNode.optString(jsonParam).toString());
			}				
		}	
	}
}